package com.ruoyi.common.core.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.context.SecurityContextHolder;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * 配置Mybatis自动填充的规则
 */
public class CreateAndUpdateMetaObjectHandler implements MetaObjectHandler {
	@Override
	public void insertFill(MetaObject metaObject) {
		Object created = getFieldValByName("createTime", metaObject);
		if (null == created) {
			//字段为空，可以进行填充
			setFieldValByName("createTime", new Date(), metaObject);
		}

		Object updated = getFieldValByName("updateTime", metaObject);
		if (null == updated) {
			//字段为空，可以进行填充
			setFieldValByName("updateTime", new Date(), metaObject);
		}

		Object createBy = getFieldValByName("createBy", metaObject);
		if (null == createBy) {
			//字段为空，可以进行填充
			setFieldValByName("createBy", SecurityContextHolder.getUserName(), metaObject);
		}

	}

	@Override
	public void updateFill(MetaObject metaObject) {
		//更新数据时，直接更新字段
		setFieldValByName("updateTime", new Date(), metaObject);
		setFieldValByName("updateBy", SecurityContextHolder.getUserName(), metaObject);
	}

}
